package com.woyao;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.woyao.core.model.BaseResponse;
import com.woyao.core.model.KeyValueList;
import com.woyao.core.model.Prefer;
import com.woyao.core.model.PreferResponse;
import com.woyao.core.service.AccountService;
import com.woyao.core.util.Common;
import com.woyao.core.util.ServiceFactory;

import java.io.IOException;
import java.util.ArrayList;

import retrofit2.Call;

import static com.woyao.WoyaoooApplication.userId;

public class PreferActivity extends AppCompatActivity {

    private TextView categoryTxt ;
    private TextView typeTxt ;
    private TextView relationTxt ;
    private TextView howTxt ;
    private TextView includeTxt ;
    private TextView temporalTxt ;
    private TextView matchatleastTxt;

    ProgressDialog progressDialog;
    private Prefer prefer = new Prefer();

    LinearLayout categoryTxtArea ;
    LinearLayout typeTxtArea ;
    LinearLayout relationTxtArea ;
    LinearLayout howTxtArea;
    LinearLayout includeTxtArea;
    LinearLayout temporalTxtArea ;


    private Integer MODIFY_CATEGORYS_CODE = 80;   //
    private Integer MODIFY_TYPES_CODE = 90;   //
    private Integer MODIFY_RELATION_CODE = 100;   //
    private Integer MODIFY_INCLUDE_CODE = 200;   //
    private Integer MODIFY_HOW_CODE = 300;   //

    ArrayList<String> list = new ArrayList<String>();
    ArrayList<Integer> days = new ArrayList<Integer>();
    ArrayList<String> matchness = new ArrayList<String>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_prefer);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        ab.setDisplayShowHomeEnabled(true); // show or hide the default home button
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setDisplayShowCustomEnabled(true); // enable overriding the default toolbar layout

        list.add("不限");
        list.add("本周内");
        list.add("本月内");
        list.add("本季度内");
        list.add("半年内");
        list.add("一年内");
        list.add("两年内");
        list.add("三年内");

        days.add(0);
        days.add(7);
        days.add(30);
        days.add(90);
        days.add(183);
        days.add(365);
        days.add(730);
        days.add(1095);

        for (int i = 0; i< 20; i++){
            matchness.add( 5 * i + "" );
        }



        categoryTxtArea = (LinearLayout)findViewById(R.id.id_prefer_category_area);
        typeTxtArea = (LinearLayout)findViewById(R.id.id_prefer_types_area);
        relationTxtArea = (LinearLayout)findViewById(R.id.id_prefer_relation_area);
        howTxtArea = (LinearLayout)findViewById(R.id.id_prefer_how_area);
        includeTxtArea = (LinearLayout)findViewById(R.id.id_prefer_include_area);
        temporalTxtArea = (LinearLayout)findViewById(R.id.id_prefer_timporal_area);

        categoryTxt  = (TextView)findViewById(R.id.id_prefer_category);
        typeTxt = (TextView)findViewById(R.id.id_prefer_types);
        relationTxt = (TextView)findViewById(R.id.id_prefer_relation);
        howTxt = (TextView)findViewById(R.id.id_prefer_how);
        includeTxt = (TextView)findViewById(R.id.id_prefer_include);
        temporalTxt = (TextView)findViewById(R.id.id_prefer_timporal);
        matchatleastTxt =  (TextView)findViewById(R.id.id_prefer_matchatleast);

        matchatleastTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ModifyMatchatleast();
            }
        });

        categoryTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ModifyCategorys();
            }
        });

        typeTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ModifyTypes();
            }
        });

        relationTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ModifyRelation();
            }
        });
        howTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ModifyHow();
            }
        });
        includeTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ModifyInclude();
            }
        });

        temporalTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ModifyTimporal();
            }
        });

        final Button cleanBtn = (Button) findViewById(R.id.id_prefer_clean);

        cleanBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                prefer = new Prefer();
                categoryTxt.setText("不限");
                typeTxt.setText("不限");
                relationTxt.setText("不限");
                includeTxt.setText("不限");
                howTxt.setText("不限");
                temporalTxt.setText("不限");
            }
        });

        final Button nextBtn = (Button) findViewById(R.id.id_prefer_finish);


        nextBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setPrefer();
            }
        });


        this.setTitle("我的偏好");
       loadPrefer();

    }

    private  Integer matchatleastIndex = 0 ;
    public void ModifyMatchatleast(){

        matchatleastIndex = prefer.getMatchatleast() / 5;


        String[] items =  (String[])matchness.toArray(new String[0]);

        AlertDialog.Builder singleChoiceDialog =
                new AlertDialog.Builder(PreferActivity.this);
        singleChoiceDialog.setTitle("选择匹配度");

        // 第二个参数是默认选项，此处设置为0
        singleChoiceDialog.setSingleChoiceItems(items, matchatleastIndex,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        matchatleastIndex = which;
                    }
                });
        singleChoiceDialog.setPositiveButton("确 定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        prefer.setMatchatleast( matchatleastIndex * 5);
                        matchatleastTxt.setText( matchatleastIndex * 5 +""  );
                        matchatleastTxt.setTextColor(Color.BLACK);
                    }
                });
        singleChoiceDialog.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
        singleChoiceDialog.show();
    }



    private  Integer temporalIndex = 0 ;
    public void ModifyTimporal(){

        for (int i = 0; i < days.size(); i++) {
            if (prefer.getTemporal().intValue() == days.get(i)){
                temporalIndex = i;
            }
        }


        String[] items =  (String[])list.toArray(new String[0]);

        AlertDialog.Builder singleChoiceDialog =
                new AlertDialog.Builder(PreferActivity.this);
        singleChoiceDialog.setTitle("选择更新日期");

        // 第二个参数是默认选项，此处设置为0
        singleChoiceDialog.setSingleChoiceItems(items, temporalIndex,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        temporalIndex = which;
                    }
                });
        singleChoiceDialog.setPositiveButton("确 定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        prefer.setTemporal( days.get(temporalIndex));
                        temporalTxt.setText(list.get(temporalIndex));
                        temporalTxt.setTextColor(Color.BLACK);
                    }
                });
        singleChoiceDialog.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
        singleChoiceDialog.show();
    }



    public  void ModifyCategorys() {
        Intent intent = new Intent();
        intent.putExtra("from", "search");
        KeyValueList kvl = new KeyValueList();
        kvl.setContent( prefer.getCategory_list() );
        intent.putExtra("category_list", kvl  );
        intent.setClass(PreferActivity.this, FilterCategory.class);
        startActivityForResult(intent, MODIFY_CATEGORYS_CODE);
    }

    public  void ModifyTypes() {
        Intent intent = new Intent();
        intent.putExtra("from", "search");
        intent.putExtra("title", "请选择寻求的资源");
        KeyValueList kvl = new KeyValueList();
        kvl.setContent( prefer.getTypes_list() );
        intent.putExtra("type_list", kvl  );
        intent.setClass(PreferActivity.this, FilterType.class);
        startActivityForResult(intent, MODIFY_TYPES_CODE);
    }
    public  void ModifyRelation() {
        Intent intent = new Intent();
        intent.putExtra("from", "chance");
        KeyValueList kvl = new KeyValueList();
        kvl.setContent( prefer.getRelation_list() );
        intent.putExtra("business", kvl  );
        intent.setClass(PreferActivity.this, FilterBusiness.class);
        startActivityForResult(intent, MODIFY_RELATION_CODE);
    }

    public  void ModifyInclude() {
        Intent intent = new Intent();
        intent.putExtra("from", "chance");

        KeyValueList kvl = new KeyValueList();
        kvl.setContent( prefer.getInclude_list() );
        intent.putExtra("include", kvl  );

        intent.setClass(PreferActivity.this, FilterLocation.class);
        startActivityForResult(intent, MODIFY_INCLUDE_CODE);
    }

    public  void ModifyHow() {
        Intent intent = new Intent();
        intent.putExtra("from", "filter");
        intent.putExtra("type", "");

        KeyValueList kvl = new KeyValueList();
        kvl.setContent( prefer.getHow_list() );
        intent.putExtra("how_list", kvl  );

        intent.setClass(PreferActivity.this, FilterHow.class);
        startActivityForResult(intent, MODIFY_HOW_CODE);
    }

    private void loadPrefer() {


        AsyncTask<Void, Void, PreferResponse> loadTask =
                new AsyncTask<Void, Void, PreferResponse>() {
                    @Override
                    protected PreferResponse doInBackground(Void... params) {
                        AccountService svc = ServiceFactory.get(AccountService.class);
                        Call<PreferResponse> responseCall = svc.getPrefer(userId);
                        try {
                            PreferResponse response = responseCall.execute().body();
                            return response;
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(final PreferResponse response) {
                        if (response != null && response.isSuccess()) {
                            prefer = response.getContent();
                            renderPerfer();
                        }
                    }
                };
        loadTask.execute((Void) null);
    }

    private void renderPerfer(){
        if (prefer.getCategory_visible()){
            categoryTxtArea.setVisibility(View.VISIBLE);
        }else{
            categoryTxtArea.setVisibility(View.GONE);
        }
        if (prefer.getTypes_visible()){
            typeTxtArea.setVisibility(View.VISIBLE);
        }else{
            typeTxtArea.setVisibility(View.GONE);
        }

        if (prefer.getInclude_visible()){
            includeTxtArea.setVisibility(View.VISIBLE);
        }else{
            includeTxtArea.setVisibility(View.GONE);
        }

        if (prefer.getRelation_visible()){
            relationTxtArea.setVisibility(View.VISIBLE);
        }else{
            relationTxtArea.setVisibility(View.GONE);
        }
        if (prefer.getHow_visible()){
            howTxtArea.setVisibility(View.VISIBLE);
        }else{
            howTxtArea.setVisibility(View.GONE);
        }
        if (prefer.getTemporal_visible()){
            temporalTxtArea.setVisibility(View.VISIBLE);
        }else{
            temporalTxtArea.setVisibility(View.GONE);
        }

        if (prefer.getCategory_list().size()>0){
            categoryTxt.setText(Common.KeyValueToNames( prefer.getCategory_list()));
            categoryTxt.setTextColor(Color.BLACK);
        }

        if (prefer.getTypes_list().size()>0){
            typeTxt.setText(Common.KeyValueToNames( prefer.getTypes_list()));
            typeTxt.setTextColor(Color.BLACK);
        }

        if (prefer.getHow_list().size()>0){
            howTxt.setText(Common.KeyValueToNames( prefer.getHow_list()));
            howTxt.setTextColor(Color.BLACK);

        }
        if (prefer.getRelation_list().size()>0){
            relationTxt.setText(Common.KeyValueToNames( prefer.getRelation_list()));
            relationTxt.setTextColor(Color.BLACK);

        }
        if (prefer.getInclude_list().size()>0){
            includeTxt.setText(Common.KeyValueToNames( prefer.getInclude_list()));
            includeTxt.setTextColor(Color.BLACK);

        }

        if (prefer.getTemporal() >0 ){
            for (int i = 0; i < days.size(); i++) {
                if (prefer.getTemporal().intValue() == days.get(i)){
                    temporalIndex = i;
                }
            }
            temporalTxt.setText(  list.get(temporalIndex));
            temporalTxt.setTextColor(Color.BLACK);
        }


        matchatleastTxt.setText(  prefer.getMatchatleast() + "");
        matchatleastTxt.setTextColor(Color.BLACK);

    }

    private  void setPrefer( ){

//        if ( prefer.getCategory_list().size() ==0){
//            Dialog alertDialog = new AlertDialog.Builder(PreferActivity.this).
//                    setTitle("信息").
//                    setMessage("请选择合作领域").
//                    setIcon(R.drawable.ic_launcher).
//                    setPositiveButton("确定", new DialogInterface.OnClickListener() {
//
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            ModifyCategorys();
//                        }
//                    }).
//                    create();
//            alertDialog.show();
//
//            return;
//        }

        AsyncTask<Void, Void, BaseResponse> task = new AsyncTask<Void, Void, BaseResponse>() {
            @Override
            protected BaseResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<BaseResponse> responseCall = svc.setPrefer(WoyaoooApplication.userId,prefer.getDemand_id(),Common.KeyValueToNos(prefer.getTypes_list()), Common.KeyValueToNos(prefer.getRelation_list()), Common.KeyValueToNos(prefer.getInclude_list()), Common.KeyValueToNos(prefer.getHow_list()),prefer.getTemporal() +"" ,  Common.KeyValueToNos(prefer.getCategory_list()),prefer.getMatchatleast() );
                BaseResponse ret = null ;
                try {
                    BaseResponse response = responseCall.execute().body();
                    ret= response;
                } catch (IOException e) {
                    e.printStackTrace();
                    ret = null;
                }
                return ret;
            }

            @Override
            protected void onPostExecute(final BaseResponse response) {
                if (response  == null){
                    Common.alert(PreferActivity.this,"发生错误，请重试");
                    return;
                }

                if (response.isSuccess()) {
                    Intent intent = new Intent();
                    setResult(666, intent);
                    finish();
                } else {
                    Dialog alertDialog = new AlertDialog.Builder(PreferActivity.this).
                            setTitle("信息").
                            setMessage(response.getMessage()).
                            setIcon(R.drawable.ic_launcher).
                            setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    if (response.getCondition().equals("charge")){
                                        Intent intent = new Intent();
                                        intent.setClass( PreferActivity.this, MoneyActivity.class);
                                        startActivity(intent);
                                    }
                                }
                            }).
                            create();
                    alertDialog.show();



                }
            }

            @Override
            protected void onCancelled() {
            }
        };
        task.execute((Void) null);

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if  (requestCode == MODIFY_CATEGORYS_CODE && resultCode ==666){
            KeyValueList thelist = (KeyValueList) data.getExtras().get("result");
            prefer.setCategory_list(thelist.getContent());
            categoryTxt.setText( Common.KeyValueToNames(prefer.getCategory_list()));
            categoryTxt.setTextColor(Color.BLACK);
        }

        if  (requestCode == MODIFY_TYPES_CODE && resultCode ==666){
            KeyValueList thelist = (KeyValueList) data.getExtras().get("result");
            prefer.setTypes_list(thelist.getContent());
            typeTxt.setText( Common.KeyValueToNames(prefer.getTypes_list()));
            typeTxt.setTextColor(Color.BLACK);
        }

        if  (requestCode == MODIFY_INCLUDE_CODE && resultCode ==666){
            KeyValueList thelist = (KeyValueList) data.getExtras().get("result");
            prefer.setInclude_list(thelist.getContent());
            includeTxt.setText( Common.KeyValueToNames(prefer.getInclude_list()));
            includeTxt.setTextColor(Color.BLACK);
        }

        if  (requestCode == MODIFY_RELATION_CODE && resultCode ==666){
            KeyValueList thelist = (KeyValueList ) data.getExtras().get("result");
            prefer.setRelation_list(thelist.getContent());
            relationTxt.setText(Common.KeyValueToNames(prefer.getRelation_list()));
            relationTxt.setTextColor(Color.BLACK);
        }

        if  (requestCode == MODIFY_HOW_CODE && resultCode ==666){
            KeyValueList thelist = (KeyValueList ) data.getExtras().get("result");
            prefer.setHow_list(thelist.getContent());
            howTxt.setText(Common.KeyValueToNames(prefer.getHow_list()));
            howTxt.setTextColor(Color.BLACK);
        }


    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent intent = new Intent();
        setResult(0, intent);
        finish();
        return true;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent();
            setResult(0, intent);
            finish();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }
}
